package it.crosato.stage.server.model.comparison;

import it.crosato.stage.shared.objects.Multiset;

public class SetsComparator implements ISetsComparator {
	
	@Override
	public double[][] getDistancesMatrix(Multiset[][] multisets) {
		
		int nOrganisms = multisets.length;
		int nPathways = multisets[0].length;
		double[][] M = new double[nOrganisms][nOrganisms];
		
		for (int i = 0; i < nPathways; i++) {
			double[][] Mpath = getSetDistanceMatrixForPathway(multisets, i);
			for (int j = 0; j < nOrganisms; j++) {
				for (int k = 0; k < nOrganisms; k++) {
					M[j][k] += Mpath[j][k]/nPathways;
				}
			}
		}
		return M;
	}
	
	/**
	 * Calcola la matrice di distanza considerando una singola via metabolica
	 * @param multisets le vie metaboliche sotto forma di multi-insiemi di
	 * reazioni o enzimi
	 * @param pathway indice della via metabolica da considerare
	 * @return la matrice delle distanze relativa alla singola via metabolica
	 */
	private double[][] getSetDistanceMatrixForPathway(Multiset[][] multisets,
			int pathway) {
		
		int nOrganisms = multisets.length;
		double[][] Mpath = new double[nOrganisms][nOrganisms];
		
		for (int i = 0; i < nOrganisms; i++) {
			for (int j = 0; j < nOrganisms; j++) {	
				Multiset multiX = multisets[i][pathway];
				Multiset multiY = multisets[j][pathway];
				Mpath[i][j] = 1 - Utilities.getSorensenIndex(multiX, multiY);
			}
		}
		return Mpath;
	}
}